package com.hellogood.yaohuo.client.basic;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.shared.entity.Cup;
import com.hellogood.yaohuo.shared.services.CupService;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

public class CupController {

	private TreeNode[] treeNodes = null;	
	private TreeGrid treeGrid = null;
	
	public CupController() {
		initData();
		initView();
	}

	public void initData() {
		CupService.Util.getInstance().getAllCupList(new GetAllAsyncCallback());
	}

	private void initView() {
		treeGrid = new TreeGrid();
		treeGrid.setFields(new TreeGridField("cup", "杯级"));
		treeGrid.setWidth("100%");
		treeGrid.setWidth100();
		treeGrid.setHeight100();
	}

	public Canvas getCanvas() {
		return treeGrid;
	}

	private class GetAllAsyncCallback implements AsyncCallback<List<Cup>> {

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(List<Cup> result) {
			if (result != null) {
				treeNodes = new TreeNode[result.size()];
				for (int i = 0; i < result.size(); i++) {
					Cup c = result.get(i);
					TreeNode r = new TreeNode();
					r.setAttribute("cup", c.getCup());					
					r.setAttribute("isOpen", true);
					r.setAttribute("parentId", "-1");
					treeNodes[i] = r;
				}

				Tree tree = new Tree();
				tree.setModelType(TreeModelType.PARENT);
				tree.setNameProperty("cup");
				tree.setRootValue("-1");
				tree.setIdField("cup");
				tree.setParentIdField("parentId");
				tree.setOpenProperty("isOpen");
				tree.setData(treeNodes);

				treeGrid.setData(tree);
			}
		}
	}
		
}
